<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { todoApi } from '../api'

const router = useRouter()
const newTodo = ref('')
const newTodoDesc = ref('')
const newTag = ref('')
const todos = ref([])
const loading = ref(false)
const error = ref('')

// 获取所有待办事项
const fetchTodos = async () => {
  loading.value = true
  error.value = ''
  try {
    const response = await todoApi.getTodos()
    todos.value = response.data
  } catch (err) {
    error.value = '获取待办事项失败'
    console.error('获取待办事项失败:', err)
  } finally {
    loading.value = false
  }
}

// 添加待办事项
const addTodo = async () => {
  if (newTodo.value.trim()) {
    loading.value = true
    error.value = ''
    try {
      const todo = {
        title: newTodo.value,
        describe: newTodoDesc.value,
        status: 0,
        star: 0
      }
      const response = await todoApi.addTodo(todo)
      if (response.code === 200) {
        todos.value.push({
          ...response.data,
          showTagInput: false
        })
      }
      newTodo.value = ''
      newTodoDesc.value = ''
    } catch (err) {
      error.value = '添加待办事项失败'
      console.error('添加待办事项失败:', err)
    } finally {
      loading.value = false
    }
  }
}

// 更新待办事项状态
const toggleTodo = async (todo) => {
  try {
    const newStatus = todo.status === 1 ? 0 : 1
    await todoApi.updateTodo({
      id : todo.id,
      status: newStatus 
    })
    todo.status = newStatus
  } catch (err) {
    error.value = '更新待办事项状态失败'
    console.error('更新待办事项状态失败:', err)
  }
}

// 更新收藏状态
const toggleFavorite = async (todo) => {
  try {
    const newStar = todo.star === 1 ? 0 : 1
    await todoApi.updateTodo({
      id : todo.id,
      star: newStar 
    })
    todo.star = newStar
  } catch (err) {
    error.value = '更新收藏状态失败'
    console.error('更新收藏状态失败:', err)
  }
}

// 显示/隐藏标签输入框
const toggleTagInput = (todo) => {
  todo.showTagInput = !todo.showTagInput
}

// 添加标签
const addTag = async (todo) => {
  if (newTag.value.trim() && !todo.tags.includes(newTag.value.trim())) {
    try {
      const updatedTags = [...todo.tags, newTag.value.trim()]
      await todoApi.updateTodo(todo.id, { tags: updatedTags })
      todo.tags = updatedTags
      newTag.value = ''
    } catch (err) {
      error.value = '添加标签失败'
      console.error('添加标签失败:', err)
    }
  }
}

// 删除标签
const removeTag = async (todo, tag) => {
  try {
    const updatedTags = todo.tags.filter(t => t !== tag)
    await todoApi.updateTodo(todo.id, { tags: updatedTags })
    todo.tags = updatedTags
  } catch (err) {
    error.value = '删除标签失败'
    console.error('删除标签失败:', err)
  }
}

// 删除待办事项
const deleteTodo = async (id) => {
  try {
    await todoApi.deleteTodo(id)
    todos.value = todos.value.filter(todo => todo.id !== id)
  } catch (err) {
    error.value = '删除待办事项失败'
    console.error('删除待办事项失败:', err)
  }
}

// 退出登录
const logout = () => {
  localStorage.removeItem('user-token')
  router.push('/login')
}

// 组件挂载时获取待办事项
onMounted(() => {
  fetchTodos()
})
</script>

<template>
  <div class="todo-app">
    <div class="left-panel">
      <div class="header">
        <h1>新建任务</h1>
      </div>
      <div class="input-container">
        <div class="input-group">
          <input 
            v-model="newTodo" 
            @keyup.enter="addTodo"
            placeholder="添加新任务..."
            type="text"
            class="title-input"
          >
          <textarea
            v-model="newTodoDesc"
            placeholder="添加描述..."
            class="desc-input"
            rows="2"
          ></textarea>
        </div>
        <button @click="addTodo" class="add-btn">添加</button>
      </div>
    </div>
    <div class="right-panel">
      <div class="header">
        <h1>待办事项</h1>
        <button @click="logout" class="logout-btn">退出登录</button>
      </div>
      <transition-group name="todo-list" tag="ul" class="todo-list">
      <li v-for="todo in todos" :key="todo.id" :class="{ completed: todo.status === 1, favorite: todo.star === 1 }">
        <div class="todo-main">
          <label class="checkbox-container">
            <input 
              type="checkbox" 
              :checked="todo.status === 1"
              @change="toggleTodo(todo)"
            >
            <span class="checkmark"></span>
          </label>
          <div class="todo-content">
            <span class="todo-text">{{ todo.title }}</span>
            <p v-if="todo.describe" class="todo-description">{{ todo.describe }}</p>
          </div>
          <button @click="toggleFavorite(todo)" class="favorite-btn" :class="{ active: todo.star === 1 }">
            <span class="star">★</span>
          </button>
          <button @click="deleteTodo(todo.id)" class="delete-btn">删除</button>
        </div>
        <div class="todo-tags">
          <div class="tags-container">
            <span v-for="tag in todo.tags" :key="tag" class="tag">
              {{ tag }}
              <button @click="removeTag(todo, tag)" class="remove-tag">×</button>
            </span>
            <button v-if="!todo.showTagInput" @click="toggleTagInput(todo)" class="add-tag-btn">添加标签</button>
          </div>
          <div v-if="todo.showTagInput" class="add-tag">
            <input 
              v-model="newTag" 
              @keyup.enter="addTag(todo)"
              @blur="toggleTagInput(todo)"
              placeholder="添加标签..."
              type="text"
              class="tag-input"
              ref="tagInput"
            >
            <button @click="addTag(todo)" class="tag-btn">+</button>
          </div>
        </div>
      </li>
    </ul>
  </transition-group>
  </div>
</template>

<style scoped>
.todo-app {
  max-width: 1200px;
  margin: 40px auto;
  padding: 32px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border-radius: 12px;
  background-color: #ffffff;
  transition: all 0.3s ease;
  display: grid;
  grid-template-columns: 350px 1fr;
  gap: 32px;
}

.todo-list-enter-active,
.todo-list-leave-active {
  transition: all 0.5s ease;
}

.todo-list-enter-from {
  opacity: 0;
  transform: translateX(30px);
}

.todo-list-leave-to {
  opacity: 0;
  transform: translateX(-30px);
}

.left-panel, .right-panel {
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 2px solid #f5f5f7;
}

h1 {
  margin: 0;
  font-size: 20px;
  color: #1d1d1f;
  font-weight: 500;
}

.logout-btn {
  padding: 8px 16px;
  background-color: #ff3b30;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.3s ease;
  font-size: 14px;
}

.logout-btn:hover {
  background-color: #d70015;
}

.input-container {
  display: flex;
  flex-direction: column;
  gap: 12px;
  position: sticky;
  top: 32px;
}

.input-group {
  display: flex;
  flex-direction: column;
  gap: 12px;
  width: 100%;
}

.title-input,
.desc-input {
  width: 100%;
  padding: 12px;
  border: 1px solid #d2d2d7;
  border-radius: 8px;
  font-size: 15px;
  transition: all 0.3s ease;
  background-color: #f5f5f7;
}

.title-input:focus,
.desc-input:focus {
  outline: none;
  border-color: #0071e3;
  background-color: #ffffff;
  box-shadow: 0 0 0 3px rgba(0, 113, 227, 0.1);
}

.desc-input {
  resize: vertical;
  min-height: 100px;
  line-height: 1.5;
}

.add-btn {
  padding: 12px 24px;
  background-color: #0071e3;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 15px;
  cursor: pointer;
  transition: all 0.3s ease;
  width: 100%;
  font-weight: 500;
}

.add-btn:hover {
  background-color: #0077ed;
  transform: translateY(-1px);
  box-shadow: 0 2px 6px rgba(0, 113, 227, 0.2);
}

.todo-list {
  list-style: none;
  padding: 0;
  margin: 0;
  max-height: calc(100vh - 100px);
  overflow-y: auto;
  scrollbar-width: thin;
  scrollbar-color: #0071e3 #f5f5f7;
}

.todo-list::-webkit-scrollbar {
  width: 8px;
}

.todo-list::-webkit-scrollbar-track {
  background: #f5f5f7;
  border-radius: 4px;
}

.todo-list::-webkit-scrollbar-thumb {
  background-color: #0071e3;
  border-radius: 4px;
}

.todo-list li {
  background-color: #f5f5f7;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 16px;
  transition: all 0.2s ease;
}

.todo-list li:hover {
  background-color: #f0f0f2;
}

.todo-main {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.todo-content {
  flex: 1;
}

.todo-text {
  font-size: 15px;
  color: #1d1d1f;
  margin-bottom: 4px;
  display: block;
}

.todo-description {
  font-size: 13px;
  color: #86868b;
  margin: 0;
}

.checkbox-container {
  position: relative;
  padding-left: 24px;
  cursor: pointer;
  user-select: none;
}

.checkbox-container input {
  position: absolute;
  opacity: 0;
  cursor: pointer;
}

.checkmark {
  position: absolute;
  top: 0;
  left: 0;
  height: 18px;
  width: 18px;
  background-color: #ffffff;
  border: 1px solid #d1d1d1;
  border-radius: 4px;
  transition: all 0.2s ease;
}

.checkbox-container:hover input ~ .checkmark {
  border-color: #0071e3;
}

.checkbox-container input:checked ~ .checkmark {
  background-color: #0071e3;
  border-color: #0071e3;
}

.checkmark:after {
  content: "";
  position: absolute;
  display: none;
}

.checkbox-container input:checked ~ .checkmark:after {
  display: block;
  left: 6px;
  top: 2px;
  width: 4px;
  height: 9px;
  border: solid white;
  border-width: 0 2px 2px 0;
  transform: rotate(45deg);
}

.favorite-btn {
  background: none;
  border: none;
  color: #86868b;
  cursor: pointer;
  font-size: 18px;
  padding: 4px 8px;
  border-radius: 6px;
  transition: all 0.2s ease;
}

.favorite-btn:hover,
.favorite-btn.active {
  color: #0071e3;
  background-color: rgba(0, 113, 227, 0.1);
}

.delete-btn {
  background-color: #ff3b30;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 13px;
  opacity: 0.9;
  transition: all 0.2s ease;
}

.delete-btn:hover {
  opacity: 1;
  transform: translateY(-1px);
}

.todo-tags {
  margin-top: 12px;
  padding-left: 36px;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  align-items: center;
}

.tag {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 2px 8px;
  background-color: #e0e0e0;
  border-radius: 12px;
  font-size: 12px;
  color: #1d1d1f;
}

.remove-tag {
  border: none;
  background: none;
  color: #86868b;
  cursor: pointer;
  padding: 0 2px;
  font-size: 14px;
}

.remove-tag:hover {
  color: #ff3b30;
}

.add-tag-btn {
  border: none;
  background: none;
  color: #0071e3;
  font-size: 12px;
  cursor: pointer;
  padding: 2px 8px;
  border-radius: 12px;
}

.add-tag-btn:hover {
  background-color: rgba(0, 113, 227, 0.1);
}

.add-tag {
  display: flex;
  gap: 6px;
  margin-top: 6px;
}

.tag-input {
  flex: 1;
  padding: 4px 8px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  font-size: 12px;
  background-color: #ffffff;
}

.tag-input:focus {
  outline: none;
  border-color: #0071e3;
  box-shadow: 0 0 0 2px rgba(0, 113, 227, 0.1);
}

.tag-btn {
  border: none;
  background-color: #0071e3;
  color: white;
  width: 20px;
  height: 20px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  line-height: 1;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.completed .todo-text,
.completed .todo-description {
  text-decoration: line-through;
  color: #86868b;
}

.favorite .todo-text {
  color: #0071e3;
  font-weight: 500;
}
</style>